//
//  SYTabBarController.m
//  LotteryClient
//
//  Created by Suny on 14-7-5.
//  Copyright (c) 2014年 CTTC. All rights reserved.
//

#import "TabViewController.h"

@interface TabViewController ()<TabBarDelegate>
{
    NSMutableArray * _viewControllers;
}


@property (nonatomic, readonly) NSUInteger  lastSelectedIndex;
@property (nonatomic, assign) BaseViewController  *selectedViewController;

@property (nonatomic,strong)UIImageView *selectedImageMask;

@end

@implementation TabViewController

#pragma mark life cycle
- (id)init
{
    self = [super init];
    if (self) {
//        self.hasNavigationBar = NO;
//        self.hasRightViewController = NO;
        self.tabBarHeight = 44;
        _selectedIndex = NSNotFound;        //do not use self.selectedIndex, which will invoke a method call
//        self.releaseViewWhileMemoryWarning = NO;
		
		
    }
    return self;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
//        self.hasNavigationBar = NO;
//        self.hasRightViewController = NO;
        self.tabBarHeight = 44;
        _selectedIndex = NSNotFound;        //do not use self.selectedIndex, which will invoke a method call
//        self.releaseViewWhileMemoryWarning = NO;
    }
    return self;
}

- (void)dealloc
{
    [self releaseChildViewControllers];
    self.viewControllers = nil;
    self.selectedViewController = nil;
    self.customTabBar.delegate = nil;
    self.customTabBar = nil;

}


#pragma mark view life cycle

- (void)loadView
{
    [super loadView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
	CGRect tabBarFrame = CGRectMake(0, CGRectGetHeight(self.view.bounds)-self.tabBarHeight, CGRectGetWidth(self.view.bounds), self.tabBarHeight);
	if (self.hasNavigationBar)
	{
		tabBarFrame.origin.y -= self.navigationBarHeight;
	}
	
 
    self.customTabBar = [[TabBar alloc] initWithFrame:tabBarFrame];
    _customTabBar.animateSelection = NO;
    _customTabBar.showBigItemCenter = self.showBigItemCenter;
    _customTabBar.delegate = self;
    _customTabBar.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    _selectedIndex = 0;
	
	self.selectedImageMask = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"tab_item_selected.png"] ];
    [self.view addSubview:self.customTabBar];
	


}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
	self.navigationController.navigationBarHidden = YES;

	if (self.selectedViewController) 
	{
		[self.selectedViewController beginAppearanceTransition:YES animated:animated];
	} 
//    if ([self.slideNavigationController currentViewController] == self)
//    {
//        [self.selectedViewController beginAppearanceTransition:YES animated:animated];
//    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
//    if ([self.slideNavigationController currentViewController] == self)
//    {
//        [self.selectedViewController beginAppearanceTransition:NO animated:animated];
//    }
	
	if (self.selectedViewController) 
	{
		[self.selectedViewController beginAppearanceTransition:NO animated:animated];
	} 
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//    if ([self.slideNavigationController currentViewController] == self)
//    {
//        [self.selectedViewController endAppearanceTransition];
//    }
	
	[self.view bringSubviewToFront:self.navigationBar];
	
	if (self.selectedViewController) 
	{
		[self.selectedViewController endAppearanceTransition];
	} 
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
//    if ([self.slideNavigationController currentViewController] == self)
//    {
//        [self.selectedViewController endAppearanceTransition];
//    }
	
	if (self.selectedViewController) 
	{
		[self.selectedViewController endAppearanceTransition];
	} 
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark
- (NSArray *)viewControllers
{
    return [_viewControllers copy];
}

- (void)setViewControllers:(NSArray *)viewControllers
{
    // make sure view loaded.
    NO_UNUSED_WARING(self.view);
	self.selectedImageMask.frame = CGRectMake(0, 0, self.view.width/[viewControllers count], self.tabBarHeight);
	
    if (_viewControllers != viewControllers)
    {
        _viewControllers = viewControllers ? [viewControllers mutableCopy] : [NSMutableArray array];
        
        _selectedIndex = NSNotFound;
        
        if ([viewControllers count] > 0)
        {
            NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:5];
            for (BaseViewController *viewController in _viewControllers)
            {
                [self addChildViewController:viewController];
                [viewController didMoveToParentViewController:self];
                
                if ([viewController isKindOfClass:[BaseViewController class]])
                {
                    [items addObject:viewController.customTabBarItem];
					viewController.customTabViewController = self;
					
                }
				else if ([viewController isKindOfClass:[UINavigationController class]])
				{
#warning navigation 没有自定义的  先使用系统的
					UINavigationController *navigation = (UINavigationController *)viewController;
					if ([navigation.viewControllers count])
					{
						BaseViewController *vController = [navigation.viewControllers objectAtIndex:0];
						[items addObject:[vController customTabBarItem]];
						vController.customTabViewController = self;

					}
				}
            }
            [self.customTabBar setItems:items animated:NO];

            self.selectedIndex = 0;
			[self.customTabBar addSubview:self.selectedImageMask];
        }
    }
}

- (void)hideCustomTabBar
{
	CGRect frame = self.customTabBar.frame;
	frame.origin = CGPointMake( -320.0, frame.origin.y);
	
	[UIView animateWithDuration:5
					 animations:^{
						 self.customTabBar.frame = frame;
					 }];
}


- (void)releaseChildViewControllers
{
    for (UIViewController *viewController in self.childViewControllers)
    {
        [viewController willMoveToParentViewController:nil];
        [viewController removeFromParentViewController];
    }
}

- (BaseViewController *)selectedViewController
{
    return self.selectedIndex == NSNotFound ? nil : [_viewControllers objectAtIndex:self.selectedIndex];
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    if (selectedIndex >= _viewControllers.count)
    {
        return;
    }
	
    if (_selectedIndex != selectedIndex)
    {
		self.selectedImageMask.left = selectedIndex * self.selectedImageMask.width;
		if (self.customTabBar.showBigItemCenter &&
			selectedIndex == (int) floor(self.customTabBar.items.count/2))
		{
			self.selectedImageMask.hidden = YES;
		}
		else
		{
			self.selectedImageMask.hidden = NO;

		}
		UIViewController * lastSelectedController = nil;
		UIViewController * selectedController = nil;
		
		if (self.selectedIndex < [_viewControllers count])
		{
			lastSelectedController = [_viewControllers objectAtIndex:self.selectedIndex];
		}
		
		if (selectedIndex < [_viewControllers count])
		{
			selectedController = [_viewControllers objectAtIndex:selectedIndex];
		}
        _selectedIndex = selectedIndex;
		
        // set frame
        selectedController.view.frame = self.view.bounds;
		
        BOOL inWindow = self.view.window != nil;
        if (inWindow)
        {
            [selectedController beginAppearanceTransition:YES animated:NO];
            [lastSelectedController beginAppearanceTransition:NO animated:NO];
        }
        
        [self.view insertSubview:selectedController.view belowSubview:self.customTabBar];
        [lastSelectedController.view removeFromSuperview];
        
        if (inWindow)
        {
            [selectedController endAppearanceTransition];
            [lastSelectedController endAppearanceTransition];
        }
		
        
        [self.view setNeedsLayout];
    }
}
//
//- (void)setSlideNavigationController:(SNSlideNavigationController *)slideNavigationController
//{
//    _slideNavigationController = slideNavigationController;
//    
//    for (SNViewController *viewController in self.viewControllers)
//    {
//        if ([viewController respondsToSelector:@selector(setSlideNavigationController:)])
//        {
//            viewController.slideNavigationController = slideNavigationController;
//        }
//    }
//}

#pragma mark Override from UIContainerViewControllerCallbacks
- (BOOL)shouldAutomaticallyForwardAppearanceMethods NS_AVAILABLE_IOS(6_0)
{
    return NO;
}

- (BOOL)automaticallyForwardAppearanceAndRotationMethodsToChildViewControllers NS_DEPRECATED_IOS(5_0,6_0) {
    return NO;
}

- (BOOL)shouldAutomaticallyForwardRotationMethods NS_AVAILABLE_IOS(6_0) {
    return NO;
}

- (BOOL)tabBar:(TabBar *)tabBar willSelectItemAtIndex:(NSUInteger)index tabBarItem:(TabBarItem *)item
{
	if (self.delegate && [self.delegate respondsToSelector:@selector(tabViewController:willChangeToIndex:)])
	{
		return [self.delegate tabViewController:self willChangeToIndex:index];
	}
	return YES;
}

#pragma mark - SNTabBarDelegate
- (void)tabBar:(TabBar *)tabBar didSelectItemAtIndex:(NSUInteger)index tabBarItem:(TabBarItem *)item
{
    
    id viewController = [self.viewControllers objectAtIndex:index];
	BOOL allowChange = YES;

	
	if (allowChange)
	{
		if (index == _selectedIndex)
		{
			if ([self.viewControllers count])
			{
				if ([viewController isKindOfClass:[UINavigationController class]])
				{
					id vc = [viewController topViewController];
					if (vc == [viewController visibleViewController])
					{
						if (vc && [vc respondsToSelector:@selector(tabViewControllerSingleTap:)])
						{
							[(id<TabBarTapDelegate>)vc tabViewControllerSingleTap:self];
						}
					}
				}
				else
				{
					if (viewController && [viewController respondsToSelector:@selector(tabViewControllerSingleTap:)])
					{
						[viewController tabViewControllerSingleTap:self];
					}
				}
			}
		}
		else
		{
			self.selectedIndex = index;
			if ([viewController isKindOfClass:[UINavigationController class]])
			{
				id vc = [viewController topViewController];
				if (vc == [viewController visibleViewController])
				{
					if (vc && [vc respondsToSelector:@selector(tabViewControllerChangeSelectTap:)])
					{
						[(id<TabBarTapDelegate>)vc tabViewControllerChangeSelectTap:self];
					}
				}
			}
			else
			{
				if (viewController && [viewController respondsToSelector:@selector(tabViewControllerChangeSelectTap:)])
				{
					[viewController tabViewControllerChangeSelectTap:self];
				}
			}
		}
	}
	
    
	
}

@end
